﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using UnityEngine;
using XUtliPoolLib;

namespace XUpdater
{
	// Token: 0x02000013 RID: 19
	public sealed class XCaching : XSingleton<XCaching>
	{
		// Token: 0x17000004 RID: 4
		// (get) Token: 0x06000033 RID: 51 RVA: 0x00002ACC File Offset: 0x00000CCC
		public string VersionServer
		{
			get
			{
				return this._version_server;
			}
		}

		// Token: 0x17000005 RID: 5
		// (get) Token: 0x06000034 RID: 52 RVA: 0x00002AE4 File Offset: 0x00000CE4
		public string HostUrl
		{
			get
			{
				return this._host_url;
			}
		}

		// Token: 0x17000006 RID: 6
		// (get) Token: 0x06000035 RID: 53 RVA: 0x00002AFC File Offset: 0x00000CFC
		public string UpdatePath
		{
			get
			{
				return this._update_path;
			}
		}

		// Token: 0x17000007 RID: 7
		// (get) Token: 0x06000036 RID: 54 RVA: 0x00002B14 File Offset: 0x00000D14
		public XDownloader Downloader
		{
			get
			{
				return this._down_loader;
			}
		}

		// Token: 0x06000037 RID: 55 RVA: 0x00002B2C File Offset: 0x00000D2C
		internal string GetLocalPath(XBundleData data)
		{
			return string.Format("{0}{1}.assetbundle", this._update_path, data.Name);
		}

		// Token: 0x06000038 RID: 56 RVA: 0x00002B54 File Offset: 0x00000D54
		internal string GetLocalUrl(XBundleData data)
		{
			bool flag = XSingleton<XUpdater>.singleton.RunTimePlatform == BuildTarget.Standalone;
			string arg;
			if (flag)
			{
				arg = "file:///";
			}
			else
			{
				arg = "file://";
			}
			string text = string.Format("{0}{1}{2}.assetbundle", arg, this._update_path, data.Name);
			XSingleton<XDebug>.singleton.AddLog("LocalURL: ", text, null, null, null, null, XDebugColor.XDebug_None);
			return text;
		}

		// Token: 0x06000039 RID: 57 RVA: 0x00002BB8 File Offset: 0x00000DB8
		public string GetLoginServerAddress(string loginType)
		{
			string ret = XSingleton<XUpdater>.singleton.login_ip_string;// XSingleton<XUpdater>.singleton.GetLoginServerAddress(loginType);
			XSingleton<XDebug>.singleton.AddLog("GetLoginServerAddress .....loginType:" + loginType + " ip:" + ret);
			return ret;
			//return "127.0.0.1:25001";
			//return "120.27.132.197:25001";
			// 			IPlatform xplatform = XSingleton<XUpdater>.singleton.XPlatform;
			// 			return xplatform.GetHostWithHttpDns(xplatform.GetLoginServer(loginType));
		}

		// Token: 0x0600003A RID: 58 RVA: 0x00002BE4 File Offset: 0x00000DE4
		internal string GetDownloadUrl(XBundleData data)
		{
			return this.MakeToken(string.Format("{0}{1}/{2}.assetbundle", this.HostUrl, XSingleton<XUpdater>.singleton.Platform, data.Name));
		}

		// Token: 0x0600003B RID: 59 RVA: 0x00002C1C File Offset: 0x00000E1C
		internal string MakeToken(string url)
		{
			return string.Format("{0}?token={1}", url, DateTime.Now.Ticks);
		}

		// Token: 0x0600003C RID: 60 RVA: 0x00002C4C File Offset: 0x00000E4C
		public override bool Init()
		{
			//IPlatform xplatform = XSingleton<XUpdater>.singleton.XPlatform;
			this._version_server = "120.27.132.197";// xplatform.GetHostWithHttpDns(xplatform.GetVersionServer());
			this._host_url = "120.27.132.197";// xplatform.GetHostUrl();
			this._md5Generator = new MD5CryptoServiceProvider();
			this._down_loader = XUpdater.XGameRoot.AddComponent<XDownloader>();
			this._update_path = Application.persistentDataPath + XCaching.UPDATE_DIRECTORY;
			return true;
		}

		// Token: 0x0600003D RID: 61 RVA: 0x00002CB8 File Offset: 0x00000EB8
		internal bool EnableCache()
		{
			bool flag = !Directory.Exists(this._update_path);
			if (flag)
			{
				XSingleton<XDebug>.singleton.AddLog("Create new path " + this._update_path, null, null, null, null, null, XDebugColor.XDebug_None);
				try
				{
					Directory.CreateDirectory(this._update_path);
					return Directory.Exists(this._update_path);
				}
				catch (Exception ex)
				{
					XSingleton<XDebug>.singleton.AddErrorLog(string.Format("Error ", ex.Message), null, null, null, null, null);
					return false;
				}
			}
			XSingleton<XDebug>.singleton.AddLog(string.Format("Path {0} exists.", this._update_path), null, null, null, null, null, XDebugColor.XDebug_None);
			return true;
		}

		// Token: 0x0600003E RID: 62 RVA: 0x00002D74 File Offset: 0x00000F74
		internal AsyncCachedRequest IsBundleCached(XBundleData bundle, uint size)
		{
			string fullpath = this.GetLocalPath(bundle);
			AsyncCachedRequest req = new AsyncCachedRequest();
			bool flag = bundle.Size < size;
			if (flag)
			{
				new Thread(delegate()
				{
					bool flag2 = File.Exists(fullpath);
					if (flag2)
					{
						byte[] bundle2 = this.LoadFile(fullpath);
						string a = this.CalculateMD5(bundle2);
						req.Cached = (a == bundle.MD5);
						req.MaybeCached = true;
					}
					req.IsDone = true;
				}).Start();
			}
			else
			{
				req.MaybeCached = File.Exists(fullpath);
				req.IsDone = true;
			}
			return req;
		}

		// Token: 0x0600003F RID: 63 RVA: 0x00002E10 File Offset: 0x00001010
		internal bool CleanCache()
		{
			string path = (Application.platform == RuntimePlatform.IPhonePlayer) ? ("/private" + this._update_path) : this._update_path;
			bool result;
			try
			{
				bool flag = Directory.Exists(path);
				if (flag)
				{
					DirectoryInfo directoryInfo = new DirectoryInfo(path);
					directoryInfo.Delete(true);
					bool flag2 = !Directory.Exists(path);
					bool flag3 = flag2;
					if (flag3)
					{
						result = this.EnableCache();
					}
					else
					{
						result = false;
					}
				}
				else
				{
					result = true;
				}
			}
			catch (Exception ex)
			{
				XSingleton<XDebug>.singleton.AddErrorLog("CleanCache error: ", ex.Message, null, null, null, null);
				result = false;
			}
			return result;
		}

		// Token: 0x06000040 RID: 64 RVA: 0x00002EB8 File Offset: 0x000010B8
		internal byte[] LoadFile(string fullpath)
		{
			return File.ReadAllBytes(fullpath);
		}

		// Token: 0x06000041 RID: 65 RVA: 0x00002ED0 File Offset: 0x000010D0
		private AsyncReadRequest LoadFileAsync(string fullpath)
		{
			AsyncReadRequest arr = new AsyncReadRequest();
			new Thread(delegate()
			{
				arr.bytes = File.ReadAllBytes(fullpath);
				arr.IsDone = true;
			}).Start();
			return arr;
		}

		// Token: 0x06000042 RID: 66 RVA: 0x00002F17 File Offset: 0x00001117
		internal void Download(XBundleData bundle, HandleFetchBundle callback, float percent)
		{
			this._down_loader.GetBundle(bundle, this.GetDownloadUrl(bundle), new HandleBundleDownload(this.OnBundleDownload), callback, percent);
		}

		// Token: 0x06000043 RID: 67 RVA: 0x00002F3C File Offset: 0x0000113C
		internal AsyncWriteRequest Download(string meta, uint size, float percent)
		{
			this._meta_awr = new AsyncWriteRequest();
			this._meta_awr.Size = size;
			this._meta_awr.Location = meta;
			this._meta_awr.Name = meta.Substring(meta.LastIndexOf('/') + 1);
			this._meta_awr.HasError = false;
			string name = meta.Substring(meta.LastIndexOf("/") + 1);
			meta = this.MakeToken(this.HostUrl + XSingleton<XUpdater>.singleton.Platform + meta);
			this._down_loader.GetMeta(meta, name, new XDownloader.HandleBytesDownload(this.OnMetaDownload), percent);
			return this._meta_awr;
		}

		// Token: 0x06000044 RID: 68 RVA: 0x00002FEC File Offset: 0x000011EC
		internal bool Extract(XBundleData bundle, HandleFetchBundle callback, float percent)
		{
			bool flag = Application.platform == RuntimePlatform.IPhonePlayer;
			bool result;
			if (flag)
			{
				bool flag2 = this._aer == null;
				if (flag2)
				{
					this._aer = new AsyncExtractRequest();
					new Thread(delegate()
					{
						string localPath = this.GetLocalPath(bundle);
						this._aer.Data = File.ReadAllBytes(localPath);
						this._aer.IsDone = true;
					}).Start();
				}
				bool isDone = this._aer.IsDone;
				if (isDone)
				{
					callback(null, this._aer.Data, bundle, false);
					this._aer.Data = null;
					this._aer = null;
					result = true;
				}
				else
				{
					result = false;
				}
			}
			else
			{
				this._down_loader.GetBundle(bundle, this.GetLocalUrl(bundle), null, callback, percent);
				result = true;
			}
			return result;
		}

		// Token: 0x06000045 RID: 69 RVA: 0x000030BC File Offset: 0x000012BC
		private void OnMetaDownload(WWW www, string error)
		{
			bool flag = string.IsNullOrEmpty(error);
			if (flag)
			{
				byte[] bs = www.bytes;
				new Thread(delegate()
				{
					try
					{
						bool needCheckFile = XSingleton<XUpdater>.singleton.NeedCheckFile;
						if (needCheckFile)
						{
							bool flag2 = Path.GetExtension(this._meta_awr.Location).Contains("ab");
							if (flag2)
							{
								bool flag3 = bs[0] != 85 || bs[1] != 110 || bs[2] != 105 || bs[3] != 116 || bs[4] != 121 || bs[5] != 70 || bs[6] != 83;
								if (flag3)
								{
									throw new Exception("Meta head check failed.");
								}
							}
						}
						string text = Path.Combine(this._update_path, "AssetBundles");
						string fileName = Path.GetFileName(this._meta_awr.Location);
						bool flag4 = !Directory.Exists(text);
						if (flag4)
						{
							Directory.CreateDirectory(text);
						}
						string text2 = Path.Combine(text, fileName);
						File.WriteAllBytes(text2, bs);
						bool needCheckFile2 = XSingleton<XUpdater>.singleton.NeedCheckFile;
						if (needCheckFile2)
						{
							Thread.Sleep(1);
							bool flag5 = this.CheckFileSize(text2, (long)((ulong)this._meta_awr.Size));
							if (!flag5)
							{
								throw new Exception("Meta File size " + this._meta_awr.Size + " not match.");
							}
							XSingleton<XUpdater>.singleton.XPlatform.SetNoBackupFlag(text2);
							this._meta_awr.IsDone = true;
						}
						else
						{
							XSingleton<XUpdater>.singleton.XPlatform.SetNoBackupFlag(text2);
							this._meta_awr.IsDone = true;
						}
					}
					catch (Exception ex)
					{
						this.OnDownloadFailed(ex.Message, this._meta_awr);
					}
				}).Start();
			}
			else
			{
				this.OnDownloadFailed(error, this._meta_awr);
			}
		}

		// Token: 0x06000046 RID: 70 RVA: 0x00003118 File Offset: 0x00001318
		private void OnDownloadFailed(string error, AsyncWriteRequest awr)
		{
			XSingleton<XDebug>.singleton.AddErrorLog("Download Meta ", awr.Name, " error: ", error, null, null);
			awr.HasError = true;
		}

		// Token: 0x06000047 RID: 71 RVA: 0x00003140 File Offset: 0x00001340
		private AsyncWriteRequest OnBundleDownload(WWW www, XBundleData bundle, string error)
		{
			AsyncWriteRequest req = new AsyncWriteRequest();
			bool flag = string.IsNullOrEmpty(error);
			if (flag)
			{
				byte[] bs = www.bytes;
				new Thread(delegate()
				{
					req.Location = this.GetLocalPath(bundle);
					try
					{
						File.WriteAllBytes(req.Location, bs);
						req.IsDone = true;
					}
					catch (Exception ex)
					{
						this.OnDownloadFailed(ex.Message, req);
					}
				}).Start();
			}
			else
			{
				this.OnDownloadFailed(error, req);
			}
			return req;
		}

		// Token: 0x06000048 RID: 72 RVA: 0x000031C8 File Offset: 0x000013C8
		internal string CalculateMD5(byte[] bundle)
		{
			byte[] value = this._md5Generator.ComputeHash(bundle);
			return BitConverter.ToString(value);
		}

		// Token: 0x06000049 RID: 73 RVA: 0x000031F0 File Offset: 0x000013F0
		internal string CalculateMD5(byte[] bundle, int offset, int count)
		{
			byte[] value = this._md5Generator.ComputeHash(bundle, offset, count);
			return BitConverter.ToString(value);
		}

		// Token: 0x0600004A RID: 74 RVA: 0x00003218 File Offset: 0x00001418
		public bool CheckFileSize(string filePath, long fileSize)
		{
			bool result;
			try
			{
				bool flag = !File.Exists(filePath);
				if (flag)
				{
					result = false;
				}
				else
				{
					FileInfo fileInfo = new FileInfo(filePath);
					result = (fileSize == fileInfo.Length);
				}
			}
			catch (Exception ex)
			{
				XSingleton<XDebug>.singleton.AddErrorLog("XCaching.CheckFileSize: " + ex.Message, null, null, null, null, null);
				result = false;
			}
			return result;
		}

		// Token: 0x0600004B RID: 75 RVA: 0x00003284 File Offset: 0x00001484
		public override void Uninit()
		{
		}

		// Token: 0x04000035 RID: 53
		private string _version_server = null;

		// Token: 0x04000036 RID: 54
		private string _host_url = null;

		// Token: 0x04000037 RID: 55
		internal static readonly string UPDATE_DIRECTORY = "/update/";

		// Token: 0x04000038 RID: 56
		private string _update_path = null;

		// Token: 0x04000039 RID: 57
		private StringBuilder _log = new StringBuilder();

		// Token: 0x0400003A RID: 58
		private XDownloader _down_loader = null;

		// Token: 0x0400003B RID: 59
		private MD5CryptoServiceProvider _md5Generator = null;

		// Token: 0x0400003C RID: 60
		private AsyncExtractRequest _aer = null;

		// Token: 0x0400003D RID: 61
		private AsyncWriteRequest _meta_awr = null;
	}
}
